package com.shangma.cn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shangma.cn.commons.http.AxiosStatus;
import com.shangma.cn.commons.page.PageBean;
import com.shangma.cn.dto.base.impl.AdminDTO;
import com.shangma.cn.dto.base.impl.BrandDTO;
import com.shangma.cn.entity.base.impl.Admin;
import com.shangma.cn.entity.base.impl.AdminRole;
import com.shangma.cn.entity.base.impl.Brand;
import com.shangma.cn.exception.base.impl.ApiException;
import com.shangma.cn.mapper.AdminMapper;
import com.shangma.cn.mapper.AdminRoleMapper;
import com.shangma.cn.mapper.BrandMapper;
import com.shangma.cn.query.impl.AdminQuery;
import com.shangma.cn.query.impl.BrandQuery;
import com.shangma.cn.service.AdminService;
import com.shangma.cn.service.BrandService;
import com.shangma.cn.service.base.impl.BaseServiceImpl;
import com.shangma.cn.transfer.base.impl.AdminTransfer;
import com.shangma.cn.transfer.base.impl.BrandTransfer;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 开发人员: 辉哥真球帅
 * 联系方式: zhengzhoudaxuevip@163.com
 * 创建时间: 2021/10/7  16:42
 * 文件含义:
 */
@Service
@RequiredArgsConstructor
@Transactional
public class AdminServiceImpl extends BaseServiceImpl<Admin> implements AdminService {


    public final AdminMapper adminMapper;
    public final AdminTransfer adminTransfer;
    public final BCryptPasswordEncoder bCryptPasswordEncoder;

    public final AdminRoleMapper adminRoleMapper;

    /**
     * 分页条件查询
     * <p>
     * if()
     * select * from brand where brand_name like "%值%" and  create_time between start end end
     */
    @Override
    public PageBean<AdminDTO> searchPage(AdminQuery adminQuery) {
        PageHelper.startPage(adminQuery.getCurrentPage(), adminQuery.getPageSize());
        List<Admin> admins = null;
        if (adminQuery.isQuery()) {
            LambdaQueryWrapper<Admin> lambda = new QueryWrapper<Admin>().lambda();
            if (!StringUtils.isEmpty(adminQuery.getAdminName())) {
                lambda.like(Admin::getAdminName, adminQuery.getAdminName());
            }

            if (!StringUtils.isEmpty(adminQuery.getCardCode())) {
                lambda.eq(Admin::getCardCode, adminQuery.getCardCode());
            }


            if (adminQuery.getStartTime() != null && adminQuery.getEndTime() != null) {
                lambda.between(Admin::getCreateTime, adminQuery.getStartTime(), adminQuery.getEndTime());
            }

            admins = adminMapper.selectList(lambda);
        } else {
            admins = adminMapper.selectList(null);
        }
        PageInfo<Admin> pageInfo = new PageInfo<>(admins);
        long total = pageInfo.getTotal();
        PageBean<AdminDTO> pageBean = new PageBean<>(total, adminTransfer.toDTOS(admins));
        return pageBean;
    }

    /**
     * select count(1) from sys_admin where id!=id and (account_name=accountName or admin_email=adminEmail or admin_phone=adminPhone or card_code=cardCode)
     *
     * @param admin
     * @return
     */
    @Override
    public boolean isContainAccountEmailPhoneCode(Admin admin) {
        if (admin.getId() == null) {
            int count = adminMapper.selectCount(new QueryWrapper<Admin>().lambda().or().eq(Admin::getAccountName, admin.getAccountName()).or().eq(Admin::getAdminEmail, admin.getAdminEmail()).or().eq(Admin::getAdminPhone, admin.getAdminPhone()).or().eq(Admin::getCardCode, admin.getCardCode()));
            return count >= 1;
        } else {
            int mzUpdate = adminMapper.isMZUpdate(admin);
            return mzUpdate >= 1;

        }


    }

    /**
     * 添加员工和员工的角色
     *
     * @param admin
     * @return
     */
    @Override
    public int addAdminAndRoles(Admin admin) {
        if (isContainAccountEmailPhoneCode(admin)) {
            throw new ApiException(AxiosStatus.ADMIN_DATA_NOT_WANSHAN);
        }
        admin.setIsEnable(false);
        admin.setAdmin(false);
        admin.setAccountPwd(bCryptPasswordEncoder.encode("123456"));
        int i = this.addEntity(admin);
        admin.getRoleIds().forEach(roleId -> adminRoleMapper.insert(new AdminRole(admin.getId(), roleId)));
        return i;
    }

    @Override
    public AdminDTO getAdminAndRolesById(Long id) {
        Admin one = this.findOne(id);
        AdminDTO adminDTO = adminTransfer.toDTO(one);
        adminDTO.setRoleIds(adminRoleMapper.selectList(new QueryWrapper<AdminRole>().lambda().eq(AdminRole::getAdminId, id)).stream().map(AdminRole::getRoleId).collect(Collectors.toList()));
        return adminDTO;
    }


    /**
     * 修改员工和员工的角色
     */
    @Override
    public int updateAdminAndRoles(Admin admin) {
        if (isContainAccountEmailPhoneCode(admin)) {
            throw new ApiException(AxiosStatus.ADMIN_DATA_NOT_WANSHAN);
        }
        //删除中间表中所有这个用户的角色
        adminRoleMapper.delete(new UpdateWrapper<AdminRole>().lambda().eq(AdminRole::getAdminId, admin.getId()));
        //添加新的角色
        admin.getRoleIds().forEach(roleId -> adminRoleMapper.insert(new AdminRole(admin.getId(), roleId)));
        return super.updateEntity(admin);
    }

    @Override
    public int deleteAdminCascadeRoles(List<Long> ids) {
        //删除中间表的内容
        adminRoleMapper.delete(new UpdateWrapper<AdminRole>().lambda().in(AdminRole::getAdminId, ids));
        return adminMapper.deleteBatchIds(ids);
    }

    @Override
    public Admin findAdminByUsername(String username) {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().lambda().eq(Admin::getAccountName, username));
        return admin;
    }


}
